﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;

using Microsoft.Research.Kinect.Nui;

namespace KinnectInput
{
    public class HandKinectSDK
    {
        public JointID ID { get; private set; }
        public Runtime MainRuntime;
        public Vector2 pos2D;
        GraphicsDevice gDev;
        public HandKinectSDK(JointID j, Runtime MainRuntime, GraphicsDevice gDev)
        {
            this.ID = j;
            this.MainRuntime = MainRuntime;
            MainRuntime.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(KinectSkelletonRuntime_FrameReady);
            pos2D = Vector2.Zero;
            this.gDev=gDev;
        }
        private void KinectSkelletonRuntime_FrameReady(object sender, SkeletonFrameReadyEventArgs e)
        {
            SkeletonFrame skeletonFrame = e.SkeletonFrame;
            foreach (SkeletonData data in skeletonFrame.Skeletons)
            {
                if (SkeletonTrackingState.Tracked == data.TrackingState)
                {
                    foreach (Joint joint in data.Joints)
                    {
                        if (this.ID == joint.ID)
                        {
                            pos2D = getDisplayPosition(joint);
                        }
                    }
                    
                }
            }
        }
        private Vector2 getDisplayPosition(Joint joint)
        {

            float depthX, depthY;
            MainRuntime.SkeletonEngine.SkeletonToDepthImage(joint.Position, out depthX, out depthY);
            //depthX = Math.Max(0, Math.Min(depthX * 320, 320));  //convert to 320, 240 space
            depthX = Math.Max(0, Math.Min(depthX * 320, gDev.Viewport.Width));//pasar  de  320 a screen space
            //depthY = Math.Max(0, Math.Min(depthY * 240, 240));  //convert to 320, 240 space
            depthY = Math.Max(0, Math.Min(depthY * 240, gDev.Viewport.Height));//de 320 ascreen space


            int colorX, colorY;
            ImageViewArea iv = new ImageViewArea();

            // only ImageResolution.Resolution640x480 is supported at this point
            MainRuntime.NuiCamera.GetColorPixelCoordinatesFromDepthPixel(ImageResolution.Resolution640x480, iv, (int)depthX, (int)depthY, (short)0, out colorX, out colorY);

            // map back to skeleton.Width & skeleton.Height
            //return new Vector2((int)(400 * colorX / 640.0), (int)(400 * colorY / 480));
            return new Vector2((int)(this.gDev.Viewport.Width * colorX / 640.0), (int)(this.gDev.Viewport.Height * colorY / 480));

        }
        
    }
}
